package admin

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"io/ioutil"
	"net/http"
	"net/url"
	"strings"
	"time"
	"zhuandan/data_source"
	"zhuandan/models"
	"zhuandan/redis_lib"
	"zhuandan/service"
	"zhuandan/utils"
)

type ProcureRBody struct {
	Data       []models.Procuresql `json:"data"`
	PageNo     int                 `json:"pageNo"`
	PageSize   int                 `json:"pageSize"`
	TotalCount int64               `json:"totalCount"`
	TotalPage  int64               `json:"totalPage"`
}

type ProcuresBody struct {
	Page           int    `json:"pageNo" from:"pageNo"`
	Phone          string `json:"phone" from:"phone"`
	Name           string `json:"name" from:"name"`
	Nickname       string `json:"nickname" from:"nickname"`
	Pagesize       int    `json:"pageSize" from:"pageSize"`
	Procuresid     int64  `json:"procuresid" from:"procuresid"`
	Classifyid     int64  `json:"classifyid" from:"classifyid"`
	Fasong         string `json:"fasong" from:"fasong"`
	State          int64  `json:"state" from:"state"`
	Status         int64  `json:"status" from:"status"`
	ID             int64  `json:"id" from:"id"`
	Uid            int64  `json:"uid" from:"uid"`
	Beizhu         string `json:"beizhu" from:"beizhu"`
	Procureorderid int64  `json:"procureorderid" from:"procureorderid"`
	Userphone      string `json:"userphone" from:"userphone"`
	Paytime        int64  `json:"paytime" from:"paytime"`
	Endtime        int64  `json:"endtime" from:"endtime"`
	Adminid        int64  `gorm:"column:adminid" json:"adminid"`
	Title          string `gorm:"column:title" json:"title"`
	Num            int64  `gorm:"column:num" json:"num"`
	Jingli         string `gorm:"column:jingli" json:"jingli"`
	Jingliname     string `gorm:"column:jingliname" json:"jingliname"`
	Huifang        string `gorm:"column:huifang" json:"huifang"`
	Laiyuanval     string `gorm:"column:laiyuanval" json:"laiyuanval"`
	Token          string `gorm:"column:token" json:"token"`
	Jieshu         int64  `gorm:"column:jieshu" json:"jieshu"`
}

func Procuresbeizhu(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	huifang := request.Huifang
	var procure models.Procure
	data_source.Db.Where("id = ?", id).First(&procure)
	if len(procure.Huifang) == 0 {
		data_source.Db.Model(&models.Procure{}).Where("id = ?", id).Update("huifang", huifang)
	} else {
		procureup := models.Procure{
			Huifang: procure.Huifang + "," + huifang,
		}
		data_source.Db.Where("id = ?", id).Updates(&procureup)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Procurephone(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	phone := request.Phone

	var users models.Procure
	data_source.Db.Select("id,title,content,phone,addtime").Where("phone =  ?", phone).Where("addtime > ?", time.Now().Unix()-86400*90).First(&users)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    users,
		"msg":     "ok",
	})
	return

}

func Procuresjieshu(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	jieshu := request.Jieshu
	id := request.ID
	adminid := request.Adminid
	data_source.Db.Model(&models.Procure{}).Where("id = ?", id).Update("jieshu", jieshu)
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "结束转单",
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

func Procures(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	classifyid := request.Classifyid
	laiyuanval := request.Laiyuanval
	paytime := request.Paytime
	endtime := request.Endtime
	name := request.Name
	fasong := request.Fasong
	phone := request.Phone
	userphone := request.Userphone
	currentPage := request.Page
	pageSize := request.Pagesize
	adminid := request.Adminid
	jingli := request.Jingli
	jingliname := request.Jingliname
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	//var users []models.Procure
	var users []models.Procuresql
	res := data_source.Db.Model(&models.Procure{}).Select("procure.*, user.nickname, user.phone as userphone, user.jingli, user.jingliname").Joins("left join user on user.id = procure.uid").Where("procure.state = 1")
	//res := data_source.Db
	if id > 0 {
		res = res.Where("procure.id = ?", id)
	}
	if paytime > 0 {
		res = res.Where("procure.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("procure.addtime < ?", endtime)
	}
	if classifyid > 0 {
		res = res.Where("procure.classifyid = ?", classifyid)
	}
	fasongs := strings.Split(fasong, ",")
	if fasong != "" && fasong != "1,2,3" {

		//res = res.Where("procure.fasong = ?", fasong)
		res = res.Where("procure.fasong in (?)", fasongs)
	}
	if name != "" {
		res = res.Where("procure.title like ? or user.nickname like ?", "%"+name+"%", "%"+name+"%")
	}
	if jingli != "" {
		res = res.Where("user.jingli = ?", jingli)
	}
	if jingliname != "" {
		res = res.Where("user.jingliname = ?", jingliname)
	}
	if phone != "" {
		res = res.Where("procure.phone like ?", "%"+phone+"%")
	}
	if laiyuanval != "" {
		res = res.Where("procure.laiyuanval like ?", "%"+laiyuanval+"%")
	}
	if userphone != "" {
		res = res.Where("user.phone = ?", userphone)
	}
	res.Model(&models.Procure{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("procure.addtime desc").Find(&users)
	var kefus []models.Adminuser
	kefus = service.Kefus()
	var pidarr []int64
	for _, u := range users {
		pidarr = append(pidarr, u.ID)
	}
	var procurelog []models.Procurelog
	data_source.Db.Where("procureid in (?)", pidarr).Find(&procurelog)

	for k, v := range users {
		var seenum int64
		for _, p := range procurelog {
			if v.ID == p.Procureid {
				seenum = seenum + 1
			}
		}
		users[k].Seenum = seenum
		for _, kf := range kefus {
			if v.Uid == kf.ID {
				users[k].Nickname = kf.Name
				users[k].Userphone = kf.Name
			}
		}
	}
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "查看所有转单记录",
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type ProcurepushsRBody struct {
	Data       []models.Pustywdsql `json:"data"`
	PageNo     int                 `json:"pageNo"`
	PageSize   int                 `json:"pageSize"`
	TotalCount int64               `json:"totalCount"`
	TotalPage  int64               `json:"totalPage"`
}

func Procurepushs(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	phone := request.Phone
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	//var users []models.Procure
	var users []models.Pustywdsql
	res := data_source.Db.Model(&models.Pustywd{}).Select("pustywd.*, user.nickname, user.phone").Joins("left join user on user.id = pustywd.uid").Where("pustywd.procureid = ?", id)

	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}

	res.Model(&models.Pustywd{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("pustywd.id desc").Find(&users)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcurepushsRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Procuresupdatesee(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	adminid := request.Adminid

	adminlog := models.Adminlog{
		Adminid: adminid,
		Addtime: time.Now().Unix(),
		Content: "查看转单详情，转单id为：" + utils.Int64string(id),
	}
	data_source.Db.Create(&adminlog)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

type ProcurelogsRBody struct {
	Data       []models.Procurelogsql `json:"data"`
	PageNo     int                    `json:"pageNo"`
	PageSize   int                    `json:"pageSize"`
	TotalCount int64                  `json:"totalCount"`
	TotalPage  int64                  `json:"totalPage"`
}

func Procurelogs(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	procuresid := request.Procuresid
	paytime := request.Paytime
	endtime := request.Endtime
	currentPage := request.Page
	pageSize := request.Pagesize
	//adminid := request.Adminid
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	//var users []models.Procure
	var procurelog []models.Procurelogsql
	res := data_source.Db.Model(&models.Procurelog{}).Select("procurelog.*, user.nickname, user.phone").Joins("left join user on user.id = procurelog.uid").Where("procurelog.procureid = ?", procuresid)
	//res := data_source.Db
	if paytime > 0 {
		res = res.Where("procurelog.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("procurelog.addtime < ?", endtime+86400)
	}

	res.Model(&models.Procurelog{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("procurelog.id desc").Find(&procurelog)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcurelogsRBody{
		Data:       procurelog,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Procuredel(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	data_source.Db.Model(&models.Procure{}).Where("id = ?", id).Update("state", 2)
	data_source.Db.Where("procureid = ?", id).Delete(&models.Infosjb{})

	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "删除转单id:" + utils.Int64string(id),
		}
		data_source.Db.Create(&adminlog)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}
func Ywdtongke(ctx *gin.Context) {
	token := Accesstokengzh()
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    token,
		"msg":     "ok",
	})
	return
}

func Tuisong(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	adminid := request.Adminid
	if adminid == 0 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "请登录",
		})
		return
	}
	var adminuser models.Adminuser
	data_source.Db.Where("id = ?", adminid).First(&adminuser)

	var procure models.Procure
	data_source.Db.Select("id,fasong,classifyid,provinceid,title").Where("id = ?", id).First(&procure)

	var users []models.User

	var baonian models.Baonian
	data_source.Db.Where("classifyid = ?", procure.Classifyid).First(&baonian)

	if baonian.ID > 0 {
		if procure.Fasong == 0 || procure.Fasong == 1 {
			var baonians []models.Baonian
			data_source.Db.Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&baonians)
			var useridarr []int64
			for _, t := range baonians {
				useridarr = append(useridarr, t.Uid)
			}
			procureup := models.Procure{
				Fasong:     2,
				Tuisongren: adminuser.Name,
				Tuisongone: time.Now().Unix(),
			}
			data_source.Db.Where("id = ?", id).Updates(&procureup)
			data_source.Db.Where("id in (?)", useridarr).Where("accept = 1").Where("ywddingyue = 2").Where("bnendtime > ?", time.Now().Unix()).Where("bninttime < ?", time.Now().Unix()).Find(&users)
			//data_source.Db.Where("id in (?)", useridarr).Where("bnendtime > ?", time.Now().Unix()).Find(&users)
			adminlog := models.Adminlog{
				Adminid: adminid,
				Addtime: time.Now().Unix(),
				Content: "第一次推送id:" + utils.Int64string(id),
			}
			data_source.Db.Create(&adminlog)
			Tuisongywdceshi(users, procure)

		} else if procure.Fasong == 2 {
			if procure.Tuisongone >= time.Now().Unix()-60*20 {
				ctx.JSON(http.StatusOK, gin.H{
					"code":    400,
					"error":   1,
					"success": 400,
					"data":    "on",
					"msg":     "距离第一次推送不足20分钟，无法继续推送",
				})
				return
			}
			var tuisongs []models.Tuisongshezhi
			data_source.Db.Where("state = 1").Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&tuisongs)
			var useridarr []int64
			for _, t := range tuisongs {
				useridarr = append(useridarr, t.Uid)
			}
			procureup := models.Procure{
				Fasong:        3,
				Tuisongrentwo: adminuser.Name,
				Tuisongtwo:    time.Now().Unix(),
			}
			data_source.Db.Where("id = ?", id).Updates(&procureup)
			data_source.Db.Select("id,unionid,ywdgzheopenid,vip,ifbuy").Where("id in (?)", useridarr).Where("ywddingyue = 2").Where("accept = 1").Find(&users)

			var userlist1 []models.User
			var userlist2 []models.User

			for _, user := range users {
				if procure.Laiyuanval == "第三方" {
					if user.Ifbuy == 2 {
						if user.Vip == 2 {
							userlist1 = append(userlist1, user)
						}
						if user.Vip == 1 {
							userlist2 = append(userlist2, user)
						}
					}
				} else {
					if user.Vip == 2 {
						userlist1 = append(userlist1, user)
					}
					if user.Vip == 1 {
						userlist2 = append(userlist2, user)
					}
				}

			}

			Tuisongywdceshi(userlist1, procure)
			Tuisongywdceshi(userlist2, procure)
			adminlog := models.Adminlog{
				Adminid: adminid,
				Addtime: time.Now().Unix(),
				Content: "第二次推送id:" + utils.Int64string(id),
			}
			data_source.Db.Create(&adminlog)

		} else if procure.Fasong == 3 {
			//ctx.JSON(http.StatusOK, gin.H{
			//	"code":    0,
			//	"error":   0,
			//	"success": 200,
			//	"data":    "ok",
			//	"msg":     "ok",
			//})
			//return
			var tuisongs []models.Tuisongshezhi
			data_source.Db.Where("state = 1").Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&tuisongs)
			var useridarr []int64
			for _, t := range tuisongs {
				useridarr = append(useridarr, t.Uid)
			}
			procureup := models.Procure{
				Fasong:        3,
				Tuisongrentwo: adminuser.Name,
				Tuisongtwo:    time.Now().Unix(),
			}
			data_source.Db.Where("id = ?", id).Updates(&procureup)
			//data_source.Db.Model(&models.Procure{}).Where("id = ?", id).Update("fasong", 3)
			data_source.Db.Select("id,unionid,ywdgzheopenid,vip").Where("id in (?)", useridarr).Where("ywddingyue = 2").Where("accept = 1").Find(&users)

			var userlist1 []models.User
			var userlist2 []models.User

			for _, user := range users {
				if procure.Laiyuanval == "第三方" {
					if user.Ifbuy == 2 {
						if user.Vip == 2 {
							userlist1 = append(userlist1, user)
						}
						if user.Vip == 1 {
							userlist2 = append(userlist2, user)
						}
					}
				} else {
					if user.Vip == 2 {
						userlist1 = append(userlist1, user)
					}
					if user.Vip == 1 {
						userlist2 = append(userlist2, user)
					}
				}
			}

			Tuisongywdceshi(userlist1, procure)
			Tuisongywdceshi(userlist2, procure)

			adminlog := models.Adminlog{
				Adminid: adminid,
				Addtime: time.Now().Unix(),
				Content: "第二次推送id:" + utils.Int64string(id),
			}
			data_source.Db.Create(&adminlog)

		}
	} else {
		var tuisongs []models.Tuisongshezhi
		data_source.Db.Where("state = 1").Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&tuisongs)

		var useridarr []int64
		for _, t := range tuisongs {
			useridarr = append(useridarr, t.Uid)
		}
		procureup := models.Procure{
			Fasong:        3,
			Tuisongrentwo: adminuser.Name,
			Tuisongren:    adminuser.Name,
			Tuisongtwo:    time.Now().Unix(),
			Tuisongone:    time.Now().Unix(),
		}
		data_source.Db.Where("id = ?", id).Updates(&procureup)
		//data_source.Db.Model(&models.Procure{}).Where("id = ?", id).Update("fasong", 3)
		data_source.Db.Select("id,unionid,ywdgzheopenid,vip").Where("id in (?)", useridarr).Where("ywddingyue = 2").Where("accept = 1").Find(&users)

		var userlist1 []models.User
		var userlist2 []models.User

		for _, user := range users {
			if procure.Laiyuanval == "第三方" {
				if user.Ifbuy == 2 {
					if user.Vip == 2 {
						userlist1 = append(userlist1, user)
					}
					if user.Vip == 1 {
						userlist2 = append(userlist2, user)
					}
				}
			} else {
				if user.Vip == 2 {
					userlist1 = append(userlist1, user)
				}
				if user.Vip == 1 {
					userlist2 = append(userlist2, user)
				}
			}
		}

		Tuisongywdceshi(userlist1, procure)
		Tuisongywdceshi(userlist2, procure)
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "第二次推送id:" + utils.Int64string(id),
		}
		data_source.Db.Create(&adminlog)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

func Tuisongzidong(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var users []models.User
	var procure models.Procure
	data_source.Db.Select("id,fasong,classifyid,provinceid,title").Where("id = ?", id).First(&procure)

	//var tuisongs []models.Tuisongshezhi
	//data_source.Db.Where("state = 1").Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&tuisongs)
	//var useridarr []int64
	//for _, t := range tuisongs {
	//	useridarr = append(useridarr, t.Uid)
	//}

	data_source.Db.Select("id,unionid,ywdgzheopenid,vip,ifbuy").Where("id = ?", 16137).Where("ywddingyue = 2").Where("accept = 1").Find(&users)
	Tuisongywdceshi(users, procure)
	//var userlist1 []models.User
	//var userlist2 []models.User

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    users,
		"msg":     "ok",
	})
	return

}

func Tuisongywd(users []models.User, procure models.Procure) {
	//fmt.Println("users----------------", users)
	ctx := context.Background()
	strval := procure.Title
	runes := []rune(strval)
	if len(runes) > 18 {
		strval = string(runes[:18])
	}
	strval = strval + ".."
	var pushadds []models.Pustywd
	var wdyuid []int64
	for _, u := range users {
		if u.Ywdgzheopenid != "" {
			//fmt.Println(u)
			data := Caigou(u.Ywdgzheopenid, strval, procure.ID, u.ID)
			jsonData, _ := json.Marshal(data)
			pushadd1 := models.Pustywd{
				Uid:       u.ID,
				Procureid: procure.ID,
				Addtime:   time.Now().Unix(),
				Content:   string(jsonData),
			}
			pushadds = append(pushadds, pushadd1)
			if data.Errcode == 43004 {
				wdyuid = append(wdyuid, u.ID)
			} else if data.Errcode == 42001 || data.Errcode == 40001 {
				resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appidywd + "&secret=" + appsecretywd)

				if err != nil {
					fmt.Println(err)
					return
				}
				defer resp.Body.Close()
				body, err := ioutil.ReadAll(resp.Body)
				r := ResponseAccess{}
				//fmt.Println("token----------", string(body))

				//把请求到的结构反序列化到专门接受返回值的对象上面
				err = json.Unmarshal(body, &r)
				if err != nil {
					fmt.Println(err)
				}
				weixintoken := r.AccessToken
				redis_lib.Client.Set(ctx, "weixinAccesstokendyewuduo", weixintoken, 7000*time.Second)
			} else if data.Errcode == 40003 {
				var weixin models.YwWeixin
				data_source.OtherDb.Select("id,openid").Where("unionid = ?", u.Unionid).First(&weixin)
				data_source.Db.Model(&models.User{}).Where("id = ?", u.ID).Update("ywdgzheopenid", weixin.Openid)
				data1 := Caigou(weixin.Openid, strval, procure.ID, u.ID)

				jsonData1, _ := json.Marshal(data1)
				pushadd := models.Pustywd{
					Uid:       u.ID,
					Procureid: procure.ID,
					Addtime:   time.Now().Unix(),
					Content:   string(jsonData1),
				}
				pushadds = append(pushadds, pushadd)
			} else {
				jsonData2, _ := json.Marshal(data)
				pushadd := models.Pustywd{
					Uid:       u.ID,
					Procureid: procure.ID,
					Addtime:   time.Now().Unix(),
					Content:   string(jsonData2),
				}
				pushadds = append(pushadds, pushadd)
			}
		}
	}
	data_source.Db.Create(&pushadds)
	data_source.Db.Model(&models.User{}).Where("id in (?)", wdyuid).Update("ywddingyue", 3)
}
func Tuisongywdceshi(users []models.User, procure models.Procure) {
	//fmt.Println("users----------------", users)
	for _, user := range users {
		task, _ := NewTuiSongTask(user, procure)
		//fmt.Println(task)
		if _, err := client.Enqueue(task); err != nil {
			fmt.Println(err)
		}
	}
}

func ConsumeTuisongywd(u models.User, procure models.Procure) {
	//fmt.Println("u----------------", u)
	ctx := context.Background()
	strval := procure.Title
	runes := []rune(strval)
	if len(runes) > 18 {
		strval = string(runes[:18])
	}
	strval = strval + ".."

	if u.Ywdgzheopenid != "" {
		//fmt.Println(u)
		data := Caigou(u.Ywdgzheopenid, strval, procure.ID, u.ID)
		jsonData, _ := json.Marshal(data)
		pushadd1 := models.Pustywd{
			Uid:       u.ID,
			Procureid: procure.ID,
			Addtime:   time.Now().Unix(),
			Content:   string(jsonData),
		}
		data_source.Db.Create(&pushadd1)
		if data.Errcode == 42001 || data.Errcode == 40001 {
			resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appidywd + "&secret=" + appsecretywd)
			if err != nil {
				fmt.Println(err)
				return
			}
			defer resp.Body.Close()
			body, err := ioutil.ReadAll(resp.Body)
			r := ResponseAccess{}
			//fmt.Println("token----------", string(body))

			//把请求到的结构反序列化到专门接受返回值的对象上面
			err = json.Unmarshal(body, &r)
			if err != nil {
				fmt.Println(err)
			}
			weixintoken := r.AccessToken
			redis_lib.Client.Set(ctx, "weixinAccesstokendyewuduo", weixintoken, 7000*time.Second)
		}
		//jsonData, _ := json.Marshal(data)
		//pushadd := models.Pustywd{
		//	Uid:       u.ID,
		//	Procureid: procure.ID,
		//	Addtime:   time.Now().Unix(),
		//	Content:   string(jsonData),
		//}
		//data_source.Db.Create(&pushadd)
		//if data.Errcode == 43004 || data.Errcode == 43101 {
		//	data_source.Db.Model(&models.User{}).Where("id = ?", u.ID).Update("ywddingyue", 1)
		//} else if data.Errcode == 42001 || data.Errcode == 40001 {
		//	resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appidywd + "&secret=" + appsecretywd)
		//	if err != nil {
		//		fmt.Println(err)
		//		return
		//	}
		//	defer resp.Body.Close()
		//	body, err := ioutil.ReadAll(resp.Body)
		//	r := ResponseAccess{}
		//	//fmt.Println("token----------", string(body))
		//
		//	//把请求到的结构反序列化到专门接受返回值的对象上面
		//	err = json.Unmarshal(body, &r)
		//	if err != nil {
		//		fmt.Println(err)
		//	}
		//	weixintoken := r.AccessToken
		//	redis_lib.Client.Set(ctx, "weixinAccesstokendyewuduo", weixintoken, 7000*time.Second)
		//
		//	data2 := Caigou(u.Ywdgzheopenid, strval, procure.ID, u.ID)
		//	jsonData1, _ := json.Marshal(data2)
		//	pushadd1 := models.Pustywd{
		//		Uid:       u.ID,
		//		Procureid: procure.ID,
		//		Addtime:   time.Now().Unix(),
		//		Content:   string(jsonData1),
		//	}
		//	data_source.Db.Create(&pushadd1)
		//}

	}

}

func Tuisongtoken(ctx *gin.Context) {

	token := Accesstokengzh()

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    token,
		"msg":     "ok",
	})
	return

}
func Tuisongrwcs(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	//token := request.Token
	var procure models.Procure
	data_source.Db.Where("id = ?", id).First(&procure)
	var tuisongs []models.Tuisongshezhi
	data_source.Db.Where("state = 1").Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&tuisongs)
	var useridarr []int64
	for _, t := range tuisongs {
		useridarr = append(useridarr, t.Uid)
	}
	var users []models.User
	data_source.Db.Select("id,unionid,ywdgzheopenid,vip").Where("id in (?)", useridarr).Where("ywddingyue != 3").Find(&users)

	var userlist1 []models.User
	var userlist2 []models.User

	for _, user := range users {
		if user.Vip == 2 {
			userlist1 = append(userlist1, user)
		}
		if user.Vip == 1 {
			userlist2 = append(userlist2, user)
		}
	}

	Tuisongywdceshi(userlist1, procure)
	Tuisongywdceshi(userlist2, procure)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}
func Typelist(ctx *gin.Context) {
	var classify []models.Classify
	data_source.Db.Find(&classify)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    classify,
		"msg":     "ok",
	})
	return

}

type TypesRBody struct {
	Data       []models.Classify `json:"data"`
	PageNo     int               `json:"pageNo"`
	PageSize   int               `json:"pageSize"`
	TotalCount int64             `json:"totalCount"`
	TotalPage  int64             `json:"totalPage"`
}

func Types(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	//var classify []models.Classifysql
	//data_source.Db.Model(&models.Classify{}).Find(&classify)

	var classify []models.Classify
	res := data_source.Db
	res.Model(&models.Classify{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("num desc").Find(&classify)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := TypesRBody{
		Data:       classify,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type TypeaddBody struct {
	ID    int64  `gorm:"column:id" json:"id"`
	Title string `gorm:"column:title" json:"title"`
	Desc  string `gorm:"column:desc" json:"desc"`
	Value string `gorm:"column:value" json:"value"`
	Num   int64  `gorm:"column:num" json:"num"`
}

func Typeupdate(ctx *gin.Context) {
	request := TypeaddBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	title := request.Title
	clssify := models.Classify{
		Title: title,
	}
	data_source.Db.Where("id = ?", id).Updates(&clssify)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

func Typeadd(ctx *gin.Context) {
	request := TypeaddBody{}
	ctx.ShouldBind(&request)
	title := request.Title
	clssify := models.Classify{
		Title: title,
	}
	data_source.Db.Create(&clssify)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

type Responsewxusermodify struct {
	Status int64  `json:"status"`
	Error  string `json:"error"`
	InfoId string `json:"info_id"`
}

func Appinfosend(info_id string) (data Responsewxusermodify) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_info_send"}, "info_id": {info_id}}
	//fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxusermodify{}
	fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type ProcureordersRBody struct {
	Data       []models.Procureorder `json:"data"`
	PageNo     int                   `json:"pageNo"`
	PageSize   int                   `json:"pageSize"`
	TotalCount int64                 `json:"totalCount"`
	TotalPage  int64                 `json:"totalPage"`
}

func Procureordersbuy(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	endtime := request.Endtime
	paytime := request.Paytime
	phone := request.Phone
	status := request.Status
	nickname := request.Nickname
	currentPage := request.Page
	pageSize := request.Pagesize
	title := request.Title
	offsetNum := pageSize * (currentPage - 1)
	var count int64

	var users []models.Procureordersql

	res := data_source.Db.Model(&models.Procureorder{}).Debug().Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime, user.nickname, procure.price").Joins("left join procure on procure.id = procureorder.procureid").Joins("left join user on user.id = procureorder.uid")
	if phone != "" {
		res = res.Where("procureorder.phone = ? or procure.phone = ?", phone, phone)
	}
	if nickname != "" {
		res = res.Where("user.nickname like ?", "%"+nickname+"%")
	}
	if status > 0 {
		res = res.Where("procureorder.status = ?", status)
	}
	if paytime > 0 {
		res = res.Where("procureorder.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("procureorder.addtime < ?", endtime+86400)
	}
	if title != "" {
		res = res.Where("procureorder.title like ?", "%"+title+"%")
	}
	res.Model(&models.Procureorder{}).Count(&count)

	res.Limit(pageSize).Offset(offsetNum).Order("procureorder.addtime desc").Find(&users)

	for k, v := range users {
		users[k].Allprice = v.Price * float64(v.Num)
	}
	var users1 []models.Procureordersql
	//if paytime > 0 && endtime > 0 {
	//	res1 := data_source.Db.Model(&models.Procureorder{}).Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime, user.nickname").Joins("left join procure on procure.id = procureorder.procureid").Joins("left join user on user.id = procureorder.uid")
	//	if phone != "" {
	//		res1 = res1.Where("procureorder.phone = ? or procure.phone", phone, phone)
	//	}
	//	if nickname != "" {
	//		res1 = res1.Where("user.nickname = ?", nickname)
	//	}
	//	if status > 0 {
	//		res1 = res1.Where("procureorder.status = ?", status)
	//	}
	//	if paytime > 0 {
	//		res1 = res1.Where("procureorder.addtime >= ?", paytime)
	//	}
	//	if endtime > 0 {
	//		res1 = res1.Where("procureorder.addtime < ?", endtime+86400)
	//	}
	//	if title != "" {
	//		res1 = res1.Where("procureorder.title like ?", "%"+title+"%")
	//	}
	//	res1.Find(&users1)
	//}

	//res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)
	var zprice float64

	for _, v := range users1 {
		zprice = zprice + v.Price*float64(v.Num)
	}
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureordertkRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
		Zprice:     zprice,
	}
	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "查看购买记录",
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Procureshouhoubuy(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	phone := request.Phone
	endtime := request.Endtime
	paytime := request.Paytime
	status := request.Status
	nickname := request.Nickname
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64

	var users []models.Procureordersql
	var users1 []models.Procureordersql
	res := data_source.Db.Model(&models.Procureorder{}).Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime, procure.fbrphone, user.nickname").Joins("left join procure on procure.id = procureorder.procureid").Joins("left join user on user.id = procureorder.uid")
	if phone != "" {
		res = res.Where("procureorder.phone = ? or procure.phone = ? or procure.fbrphone = ?", phone, phone, phone)
	}
	if nickname != "" {
		res = res.Where("user.nickname = ?", nickname)
	}
	if status > 0 {
		res = res.Where("procureorder.status = ?", status)
	} else {
		res = res.Where("procureorder.status > 2")
	}
	if paytime > 0 {
		res = res.Where("procureorder.tktime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("procureorder.tktime < ?", endtime+86400)
	}
	res.Model(&models.Procureorder{}).Count(&count)
	res.Find(&users1)
	res.Limit(pageSize).Offset(offsetNum).Order("procureorder.updatetime desc").Find(&users)

	//res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)
	for k, v := range users {
		users[k].Allprice = v.Price * float64(v.Num)
	}
	var zprice float64
	for _, v := range users1 {
		if v.Status == 4 {
			zprice = zprice + v.Price*float64(v.Num)
		}
	}
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureordertkRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
		Zprice:     zprice,
	}
	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "查看售后退款记录",
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type ProcureordersxiaoshouRBody struct {
	Data       []models.Userprice `json:"data"`
	PageNo     int                `json:"pageNo"`
	PageSize   int                `json:"pageSize"`
	TotalCount int64              `json:"totalCount"`
	TotalPage  int64              `json:"totalPage"`
}

func Procureordersxiaoshou(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	uid := request.Uid
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64

	var users []models.Userprice
	res := data_source.Db.Where("uid = ?", uid)
	res.Model(&models.Userprice{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)
	//res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)
	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureordersxiaoshouRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type ProcureordertkRBody struct {
	Data       []models.Procureordersql `json:"data"`
	PageNo     int                      `json:"pageNo"`
	PageSize   int                      `json:"pageSize"`
	TotalCount int64                    `json:"totalCount"`
	TotalPage  int64                    `json:"totalPage"`
	Zprice     float64                  `json:"zprice"`
}

func Procureordertk(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Procureordersql
	res := data_source.Db.Model(&models.Procureorder{}).Select("procureorder.*, procure.province, procure.city, procure.content, procure.name, procure.phone as khphone, procure.addtime as fbaddtime").Joins("left join procure on procure.id = procureorder.procureid").Where("procureorder.status = 3 or procureorder.status = 4 or procureorder.status = 5")
	res.Model(&models.Procureorder{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("procureorder.id desc").Find(&users)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := ProcureordertkRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Procuretksh(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	beizhu := request.Beizhu

	//var procureorder models.Procureorder
	//data_source.Db.Where("id = ?", id).First(&procureorder)
	//dqtime := time.Now().Unix() - 86400*3
	//if procureorder.Addtime+86400*3 < dqtime {
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    400,
	//		"error":   1,
	//		"success": 400,
	//		"data":    "on",
	//		"msg":     "退款时间已过",
	//	})
	//	return
	//}

	proupdata := models.Procureorder{
		Status:     3,
		Tuikuan:    beizhu,
		Tktime:     time.Now().Unix(),
		Updatetime: time.Now().Unix(),
	}

	data_source.Db.Where("id = ?", id).Updates(&proupdata)

	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "审核售后退款 id：" + utils.Int64string(id),
		}
		data_source.Db.Create(&adminlog)
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Procuretkqz(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "强制退款id：" + utils.Int64string(id),
		}
		data_source.Db.Create(&adminlog)
	}
	var porder models.Procureorder
	data_source.Db.Where("id = ?", id).First(&porder)
	if porder.Status == 4 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "无法退款",
		})
		return
	}
	if porder.Status == 3 || porder.Status == 1 {
		proupdata := models.Procureorder{
			Status:     4,
			Updatetime: time.Now().Unix(),
		}
		data_source.Db.Where("id = ?", id).Updates(&proupdata)
	} else if porder.Status == 2 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "无法退款",
		})
		return
	}

	price := porder.Price * float64(porder.Num)

	var user_info models.User
	data_source.Db.Where("id = ?", porder.Uid).First(&user_info)

	//data := Appaccountuser(user_info.Unionid)
	//fmt.Println(data)
	userprice := user_info.Price + price
	data_source.Db.Model(&models.User{}).Where("id = ?", porder.Uid).Update("price", userprice)

	userpricenew := models.Userpricenew{
		Uid:     porder.Uid,
		Addtime: time.Now().Unix(),
		State:   1,
		Price:   price,
		Title:   "退款成功，增加余额",
		Dqprice: userprice,
	}
	data_source.Db.Create(&userpricenew)

	data_source.Db.Model(&models.Procure{}).Where("id = ?", porder.Procureid).UpdateColumn("buynum", gorm.Expr("buynum - ?", porder.Num))

	if porder.Fbuid > 1000 {
		var usertor models.User
		data_source.Db.Where("id = ?", porder.Fbuid).First(&usertor)
		data_source.Db.Model(&models.User{}).Where("id = ?", porder.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx - ?", price))
		userdsx := models.Userdsx{
			Uid:     porder.Fbuid,
			Price:   price,
			Title:   "退款成功，减少待生效金额",
			Addtime: time.Now().Unix(),
			Zqprice: usertor.Dsx,
		}
		data_source.Db.Create(&userdsx)
	}

	//r := Appaccountmoney(user_info.Unionid, "退款成功", "1", price)
	//if r.Status == 1 {
	//
	//	data_source.Db.Model(&models.Procureorder{}).Where("id = ?", id).Update("tkdaozhang", 2)
	//}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Procuretkqznum(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	adminid := request.Adminid
	num := request.Num
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "强制退款id：" + utils.Int64string(id),
		}
		data_source.Db.Create(&adminlog)
	}
	var porder models.Procureorder
	data_source.Db.Where("id = ?", id).First(&porder)
	if porder.Num < num {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "无法退款",
		})
		return
	}

	price := porder.Price * float64(num)

	var user_info models.User
	data_source.Db.Where("id = ?", porder.Uid).First(&user_info)
	//data := Appaccountuser(user_info.Unionid)
	//fmt.Println(data)
	userprice := user_info.Price + price
	data_source.Db.Model(&models.User{}).Where("id = ?", porder.Uid).Update("price", userprice)
	data_source.Db.Model(&models.User{}).Where("id = ?", porder.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx - ?", price))
	data_source.Db.Model(&models.Procureorder{}).Where("id = ?", id).UpdateColumn("num", gorm.Expr("num - ?", num))

	data_source.Db.Model(&models.Procure{}).Where("id = ?", porder.Procureid).UpdateColumn("buynum", gorm.Expr("buynum - ?", num))
	//data_source.Db.Model(&models.Procureorder{}).Where("id = ?", id).Update("tkdaozhang", 2)

	userpricenew := models.Userpricenew{
		Uid:     porder.Uid,
		Addtime: time.Now().Unix(),
		State:   1,
		Price:   price,
		Title:   "退款成功，增加余额",
		Dqprice: userprice,
	}
	data_source.Db.Create(&userpricenew)
	//r := Appaccountmoney(user_info.Unionid, "退款成功", "1", price)
	//if r.Status == 1 {
	//
	//
	//}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Procuretkqzerci(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID

	var porder models.Procureorder
	data_source.Db.Where("id = ?", id).First(&porder)
	if porder.Daozhang == 2 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "无法退款",
		})
		return
	}
	if porder.Status != 4 {
		ctx.JSON(http.StatusOK, gin.H{
			"code":    400,
			"error":   1,
			"success": 400,
			"data":    "on",
			"msg":     "无法退款",
		})
		return
	}
	price := porder.Price * float64(porder.Num)

	var user_info models.User
	data_source.Db.Where("id = ?", porder.Uid).First(&user_info)
	//data := Appaccountuser(user_info.Unionid)
	//fmt.Println(data)
	userprice := user_info.Price + price
	data_source.Db.Model(&models.User{}).Where("id = ?", porder.Uid).Update("price", userprice)
	data_source.Db.Model(&models.User{}).Where("id = ?", porder.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx - ?", price))

	data_source.Db.Model(&models.Procure{}).Where("id = ?", porder.Procureid).UpdateColumn("buynum", gorm.Expr("buynum - ?", porder.Num))
	procuorderupdate := models.Procureorder{
		Tkdaozhang: 2,
		Status:     4,
	}
	data_source.Db.Where("id = ?", id).Updates(&procuorderupdate)

	userpricenew := models.Userpricenew{
		Uid:     porder.Uid,
		Addtime: time.Now().Unix(),
		State:   1,
		Price:   price,
		Title:   "退款成功，增加余额",
		Dqprice: userprice,
	}
	data_source.Db.Create(&userpricenew)
	//r := Appaccountmoney(user_info.Unionid, "退款成功", "1", price)
	//if r.Status == 1 {
	//
	//}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Procuretkly(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	beizhu := request.Beizhu
	proupdata := models.Procureorder{
		Status:     5,
		Tkliyou:    beizhu,
		Updatetime: time.Now().Unix(),
	}
	data_source.Db.Where("id = ?", id).Updates(&proupdata)
	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "拒绝退款id:" + utils.Int64string(id),
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Procuregxsl(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	id := request.ID
	var procure models.Procure
	data_source.Db.Where("id = ?", id).First(&procure)
	Appaccountmodify(utils.Int64string(4-procure.Buynum), procure.InfoId)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}

func Appaccountmodify(remain, infoid string) (data Responsewxuserdata) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_info_num_modify"}, "total": {"4"}, "remain": {remain}, "info_id": {infoid}}
	//fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxuserdata{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type Responsewxuserdata struct {
	Status int64          `json:"status"`
	User   Responsewxuser `json:"user"`
}
type Responsewxuser struct {
	AccountId  string `json:"account_id"`
	Nickname   string `json:"nickname"`
	Headimgurl string `json:"headimgurl"`
	Mobile     string `json:"mobile"`
	Money      string `json:"money"`
}

func Appaccountuser(unionid string) (data Responsewxuserdata) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_account_user"}, "unionid": {unionid}}
	//fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxuserdata{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

func Appaccountmoney(unionid, memo, typezf string, money float64) (data Responsewxuserdata) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_account_money_change"}, "unionid": {unionid}, "type": {typezf}, "money": {utils.FloatToStr64(money)}, "memo": {memo}}
	fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxuserdata{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

type TixianlistRBody struct {
	Data       []models.Usertixiansql `json:"data"`
	PageNo     int                    `json:"pageNo"`
	PageSize   int                    `json:"pageSize"`
	TotalCount int64                  `json:"totalCount"`
	TotalPage  int64                  `json:"totalPage"`
	Txyue      float64                `json:"txyue"`
	Txtgzh     float64                `json:"txtgzh"`
	Txtyhk     float64                `json:"txtyhk"`
}

func Tixianlist(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	endtime := request.Endtime
	paytime := request.Paytime
	state := request.State
	status := request.Status
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64

	var users []models.Usertixiansql
	var users1 []models.Usertixiansql
	res := data_source.Db.Model(&models.Usertixian{}).Select("usertixian.*, user.phone, user.nickname").Joins("left join user on user.id = usertixian.uid")
	if status > 0 {
		res = res.Where("usertixian.status = ?", status)
	}
	if state > 0 {
		res = res.Where("usertixian.state = ?", state)
	}
	if paytime > 0 {
		res = res.Where("usertixian.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("usertixian.addtime < ?", endtime+86400)
	}
	res.Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("usertixian.id desc").Find(&users)
	if paytime > 0 && endtime > 0 {

		res1 := data_source.Db.Model(&models.Usertixian{}).Select("usertixian.*, user.phone, user.nickname").Joins("left join user on user.id = usertixian.uid")
		if status > 0 {
			res1 = res1.Where("usertixian.status = ?", status)
		}
		if state > 0 {
			res1 = res1.Where("usertixian.state = ?", state)
		}
		if paytime > 0 {
			res1 = res1.Where("usertixian.addtime >= ?", paytime)
		}
		if endtime > 0 {
			res1 = res1.Where("usertixian.addtime < ?", endtime+86400)
		}
		res1.Find(&users1)

	}
	var bankidarr []int64
	for _, v := range users {
		if v.Bankid > 0 {
			bankidarr = append(bankidarr, v.Bankid)
		}
	}
	if len(bankidarr) > 0 {
		var banks []models.Bank
		data_source.Db.Where("id in (?)", bankidarr).Find(&banks)

		for k, v := range users {
			for _, b := range banks {
				if v.Bankid == b.ID {
					users[k].Bank = b
				}
			}
		}

	}

	var txyue float64
	var txtgzh float64
	var txtyhk float64
	for _, v := range users1 {
		if v.State == 1 {
			txyue = txyue + v.Price
		}
		if v.State == 2 {
			txtgzh = txtgzh + v.Price
		}
		if v.State == 3 {
			txtyhk = txtyhk + v.Price
		}
	}
	var totalPage int64
	if count > 0 {
		mo := count % int64(pageSize)
		if mo > 0 {
			totalPage = count/int64(pageSize) + 1
		} else {
			totalPage = count / int64(pageSize)
		}
	}

	data := TixianlistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
		Txtgzh:     txtgzh,
		Txyue:      txyue,
		Txtyhk:     txtyhk,
	}
	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "查看提现记录",
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Tixianwc(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)

	id := request.ID
	data_source.Db.Model(&models.Usertixian{}).Where("id = ?", id).Update("status", 2)
	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "点击提现完成",
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

type ProcureBody struct {
	ID         int64   `gorm:"column:id" json:"id"`
	Uid        int64   `gorm:"column:uid" json:"uid"`
	Provinceid int64   `gorm:"column:provinceid" json:"provinceid"`
	Cityid     int64   `gorm:"column:cityid" json:"cityid"`
	Countyid   int64   `gorm:"column:countyid" json:"countyid"`
	Title      string  `gorm:"column:title" json:"title"`     //  标题
	Content    string  `gorm:"column:content" json:"content"` //  描述
	Num        int64   `gorm:"column:num" json:"num"`
	Price      float64 `gorm:"column:price" json:"price"`
	Name       string  `gorm:"column:name" json:"name"`
	Phone      string  `gorm:"column:phone" json:"phone"`
	Fbrphone   string  `gorm:"column:fbrphone" json:"fbrphone"`
	Classifyid int64   `gorm:"column:classifyid" json:"classifyid"`
	Adminid    int64   `gorm:"column:adminid" json:"adminid"`
	Laiyuanval string  `gorm:"column:laiyuanval" json:"laiyuanval"`
}

func Procureadd(ctx *gin.Context) {
	request := ProcureBody{}
	ctx.ShouldBind(&request)
	//uid := request.Uid
	provinceid := request.Provinceid
	laiyuanval := request.Laiyuanval
	cityid := request.Cityid
	countyid := request.Countyid
	title := request.Title
	content := request.Content
	num := request.Num
	price := request.Price
	name := request.Name
	phone := request.Phone
	classifyid := request.Classifyid
	fbrphone := request.Fbrphone
	adminid := request.Adminid
	var province models.Citynew
	data_source.Db.Where("code = ?", provinceid).Where("level = 0").First(&province)
	var city models.Citynew
	data_source.Db.Where("code = ?", cityid).Where("level = 1").First(&city)
	var county models.Citynew
	data_source.Db.Where("code = ?", countyid).Where("level = 2").First(&county)
	var user models.User
	data_source.Db.Where("phone = ?", phone).First(&user)
	//
	//if user.ID == 0 {
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    400,
	//		"error":   0,
	//		"success": 400,
	//		"data":    "找不到用户",
	//		"msg":     "发布失败",
	//	})
	//	return
	//}
	if user.ID > 0 {
		adminid = user.ID
	}
	var classify models.Classify
	data_source.Db.Where("id = ?", classifyid).First(&classify)
	pro := models.Procure{
		Uid:           adminid,
		Province:      province.Name,
		Provinceid:    provinceid,
		City:          city.Name,
		Cityid:        cityid,
		County:        county.Name,
		Countyid:      countyid,
		Title:         title,
		Content:       content,
		Num:           num,
		Price:         price,
		Name:          name,
		Phone:         phone,
		Classifyid:    classifyid,
		Classifyvalue: classify.Value,
		Classifytitle: classify.Title,
		Addtime:       time.Now().Unix(),
		State:         1,
		Fbrphone:      fbrphone,
		Fasong:        1,
		Laiyuanval:    laiyuanval,
		Jieshu:        1,
	}
	data_source.Db.Create(&pro)

	//var provinceinfo models.City
	//data_source.Db.Where("type = 1").Where("name = ?", province.Name).First(&provinceinfo)
	//var cityinfo models.City
	//data_source.Db.Where("type = 2").Where("name = ?", city.Name).First(&cityinfo)
	//
	//info := models.Infosjb{
	//	Classifysjbid: classifyid,
	//	Typesjbid:     1,
	//	Provinceid:    provinceinfo.ID,
	//	Province:      province.Name,
	//	Cityid:        cityinfo.ID,
	//	Cityname:      city.Name,
	//	Title:         title,
	//	Content:       content,
	//	Price:         price,
	//	Username:      procure.Name,
	//	Phone:         procure.Phone,
	//	Num:           procure.Num,
	//	Addtime:       time.Now().Unix(),
	//	Procureid:     procure.ID,
	//	Status:        1,
	//}
	//data_source.Db.Create(&info)

	//url := "http://h.suishilian.com/detail/" + utils.Int64string(pro.ID)
	//var areaarr []string
	//var areacodearr []string
	//areaarr = append(areaarr, province.Name)
	//areaarr = append(areaarr, city.Name)
	//areaarr = append(areaarr, county.Name)
	//areacodearr = append(areacodearr, utils.Int64string(provinceid))
	//areacodearr = append(areacodearr, utils.Int64string(cityid))
	//areacodearr = append(areacodearr, utils.Int64string(countyid))
	//
	//area := strings.Join(areaarr, " ")
	//areacode := strings.Join(areacodearr, ",")
	//
	//res := Appinfomodify(classify.Value, title, name, phone, utils.Int64string(num), content, "1", area, areacode, url, price)
	//if res.InfoId != "" {
	//	data_source.Db.Model(&models.Procure{}).Where("id = ?", pro.ID).Update("info_id", res.InfoId)
	//	data_source.Db.Model(&models.Classify{}).Where("id = ?", classifyid).UpdateColumn("num", gorm.Expr("num + 1"))
	//	//Appinfosend(res.InfoId)
	//} else {
	//	data_source.Db.Where("id = ?", pro.ID).Delete(&models.Procure{})
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    400,
	//		"error":   0,
	//		"success": 400,
	//		"data":    "发布失败",
	//		"msg":     "发布失败",
	//	})
	//	return
	//}

	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "后台发布转单:" + utils.Int64string(pro.ID),
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Procureupdate(ctx *gin.Context) {
	request := ProcureBody{}
	ctx.ShouldBind(&request)
	title := request.Title
	content := request.Content
	num := request.Num
	price := request.Price
	name := request.Name
	phone := request.Phone
	classifyid := request.Classifyid
	provinceid := request.Provinceid
	cityid := request.Cityid
	countyid := request.Countyid
	//fbrphone := request.Fbrphone
	laiyuanval := request.Laiyuanval
	var province models.Citynew
	data_source.Db.Where("code = ?", provinceid).Where("level = 0").First(&province)
	var city models.Citynew
	data_source.Db.Where("code = ?", cityid).Where("level = 1").First(&city)
	var county models.Citynew
	data_source.Db.Where("code = ?", countyid).Where("level = 2").First(&county)
	id := request.ID
	var classify models.Classify
	data_source.Db.Where("id = ?", classifyid).First(&classify)
	pro := models.Procure{
		Province:      province.Name,
		Provinceid:    provinceid,
		City:          city.Name,
		Cityid:        cityid,
		County:        county.Name,
		Countyid:      countyid,
		Title:         title,
		Content:       content,
		Num:           num,
		Price:         price,
		Name:          name,
		Phone:         phone,
		Classifyid:    classifyid,
		Classifyvalue: classify.Value,
		Classifytitle: classify.Title,
		Updatetime:    time.Now().Unix(),
		Laiyuanval:    laiyuanval,
	}
	data_source.Db.Where("id = ?", id).Updates(&pro)

	info := models.Infosjb{
		Classifysjbid: classifyid,
		Title:         title,
		Content:       content,
		Price:         price,
		Username:      name,
		Phone:         phone,
		Num:           num,
		Addtime:       time.Now().Unix(),
	}
	data_source.Db.Where("procureid = ?", id).Updates(&info)

	//var procure models.Procure
	//data_source.Db.Where("id = ?", id).First(&procure)
	//
	//if procure.InfoId != "" {
	//
	//	url := "http://h.suishilian.com/detail/" + utils.Int64string(id)
	//	var areaarr []string
	//	var areacodearr []string
	//	areaarr = append(areaarr, procure.Province)
	//	areaarr = append(areaarr, procure.City)
	//	areaarr = append(areaarr, procure.County)
	//	areacodearr = append(areacodearr, utils.Int64string(procure.Provinceid))
	//	areacodearr = append(areacodearr, utils.Int64string(procure.Cityid))
	//	areacodearr = append(areacodearr, utils.Int64string(procure.Countyid))
	//
	//	area := strings.Join(areaarr, " ")
	//	areacode := strings.Join(areacodearr, ",")
	//
	//	Appinfomodifyup(classify.Value, title, name, phone, utils.Int64string(num), content, "1", area, areacode, url, procure.InfoId, price)
	//	data_source.Db.Model(&models.Procure{}).Where("id = ?", id).Update("fasong", 1)
	//
	//}

	adminid := request.Adminid
	if adminid > 0 {
		adminlog := models.Adminlog{
			Adminid: adminid,
			Addtime: time.Now().Unix(),
			Content: "后台修改转单:" + utils.Int64string(id),
		}
		data_source.Db.Create(&adminlog)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return
}
func Appinfomodify(itemtype, title, contact_name, contact_tel, num, content, status, area, area_code, other_url string, money float64) (data Responsewxusermodify) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_info_modify"}, "item_type": {itemtype}, "title": {title}, "contact_name": {contact_name}, "contact_tel": {contact_tel}, "num": {num}, "content": {content}, "status": {status}, "area": {area}, "area_code": {area_code}, "other_url": {other_url}, "source_type": {"转单宝"}, "total": {"4"}, "price": {utils.FloatToStr64(money)}}
	//fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxusermodify{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

func Appinfomodifyup(itemtype, title, contact_name, contact_tel, num, content, status, area, area_code, other_url, info_id string, money float64) (data Responsewxusermodify) {
	value := url.Values{"token": {"yanwei123yanwei123yanwei123yanwe"}, "action": {"app_info_modify"}, "info_id": {info_id}, "item_type": {itemtype}, "title": {title}, "contact_name": {contact_name}, "contact_tel": {contact_tel}, "num": {num}, "content": {content}, "status": {status}, "area": {area}, "area_code": {area_code}, "other_url": {other_url}, "source_type": {"转单宝"}, "total": {"4"}, "price": {utils.FloatToStr64(money)}}
	//fmt.Println(value)
	resp, err := http.PostForm("https://data.yewudaotech.com/interface.php", value)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	r := Responsewxusermodify{}
	//fmt.Println(string(body))

	//把请求到的结构反序列化到专门接受返回值的对象上面
	err = json.Unmarshal(body, &r)
	if err != nil {
		fmt.Println(err)
	}
	return r
}

func Typecl(ctx *gin.Context) {
	var classify []models.Classify
	data_source.Db.Find(&classify)
	for _, v := range classify {
		var num int64
		data_source.Db.Model(&models.Procure{}).Where("classifyid = ?", v.ID).Count(&num)
		data_source.Db.Model(&models.Classify{}).Where("id = ?", v.ID).Update("num", num)
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    classify,
		"msg":     "ok",
	})
	return

}

type ZhuanfalogsRBody struct {
	Data       []models.Zhuanfalogsql `json:"data"`
	PageNo     int                    `json:"pageNo"`
	PageSize   int                    `json:"pageSize"`
	TotalCount int64                  `json:"totalCount"`
	TotalPage  int64                  `json:"totalPage"`
}

func Zhuanfalogs(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	endtime := request.Endtime
	paytime := request.Paytime
	phone := request.Phone
	nickname := request.Nickname
	currentPage := request.Page
	pageSize := request.Pagesize
	title := request.Title
	offsetNum := pageSize * (currentPage - 1)
	var count int64

	var users []models.Zhuanfalogsql

	res := data_source.Db.Model(&models.Zhuanfalog{}).Select("zhuanfalog.*, procure.title, user.nickname, user.phone").Joins("left join procure on procure.id = zhuanfalog.procureid").Joins("left join user on user.id = zhuanfalog.uid")
	if phone != "" {
		res = res.Where("user.phone = ?", phone)
	}
	if nickname != "" {
		res = res.Where("user.nickname like ?", "%"+nickname+"%")
	}
	if paytime > 0 {
		res = res.Where("zhuanfalog.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("zhuanfalog.addtime < ?", endtime)
	}
	if title != "" {
		res = res.Where("procure.title like ?", "%"+title+"%")
	}
	res.Model(&models.Zhuanfalog{}).Count(&count)

	res.Limit(pageSize).Offset(offsetNum).Order("zhuanfalog.id desc").Find(&users)
	var totalPage int64
	if count > 0 {
		mo := count % int64(pageSize)
		if mo > 0 {
			totalPage = count/int64(pageSize) + 1
		} else {
			totalPage = count / int64(pageSize)
		}
	}

	data := ZhuanfalogsRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type AdminlogosRBody struct {
	Data       []models.Adminlogsql `json:"data"`
	PageNo     int                  `json:"pageNo"`
	PageSize   int                  `json:"pageSize"`
	TotalCount int64                `json:"totalCount"`
	TotalPage  int64                `json:"totalPage"`
}

func Adminlogos(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	paytime := request.Paytime
	endtime := request.Endtime
	currentPage := request.Page
	pageSize := request.Pagesize
	adminid := request.Adminid
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	//var users []models.Procure
	var adminlgo []models.Adminlogsql
	res := data_source.Db.Model(&models.Adminlog{}).Select("adminlog.*, adminuser.name as adminname").Joins("left join adminuser on adminuser.id = adminlog.adminid")
	//res := data_source.Db
	if paytime > 0 {
		res = res.Where("adminlog.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("adminlog.addtime < ?", endtime+86400)
	}
	if adminid > 0 {
		res = res.Where("adminlog.adminid = ?", adminid)
	}
	res.Model(&models.Adminlog{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("adminlog.id desc").Find(&adminlgo)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := AdminlogosRBody{
		Data:       adminlgo,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

func Tuisongrw(ctx *gin.Context) {

	var tsrws []models.Tuisongrenwu
	data_source.Db.Where("tuisong = 1").Where("tuisong < ?", time.Now().Unix()-100).Find(&tsrws)
	data_source.Db.Model(&models.Tuisongrenwu{}).Where("tuisong = 1").Where("tuisong < ?", time.Now().Unix()-100).Update("tuisong", 2)
	for _, v := range tsrws {
		var procure models.Procure
		data_source.Db.Where("id = ?", v.Procureid).First(&procure)
		var tuisongs []models.Tuisongshezhi
		data_source.Db.Where("state = 1").Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&tuisongs)

		//var baonians []models.Baonian
		//data_source.Db.Where("provinceid = ?", procure.Provinceid).Where("classifyid = ?", procure.Classifyid).Find(&baonians)

		var useridarr []int64
		for _, t := range tuisongs {
			useridarr = append(useridarr, t.Uid)
		}

		var users []models.User
		data_source.Db.Select("id,unionid,ywdgzheopenid,vip").Where("id in (?)", useridarr).Where("ywddingyue != 3").Where("vip = 1").Find(&users)
		//data_source.Db.Where("id = ?", "26280").Find(&users)

		var userlist []models.User
		data_source.Db.Select("id,unionid,ywdgzheopenid,classifyids,provincecodes").Where("classifyids like ?", procure.Classifyid).Where("provincecodes = ?", "").Where("vip = 1").Where("ywddingyue != 3").Find(&userlist)

		for _, us := range userlist {
			typelist := strings.Split(us.Classifyids, ",")
			for _, ty := range typelist {

				if procure.Classifyid == utils.StrToInt64(ty) {
					users = append(users, us)
					break
				}
			}
		}

		strval := procure.Title
		runes := []rune(strval)
		if len(runes) > 18 {
			strval = string(runes[:18])
		}
		strval = strval + ".."
		var pushadds []models.Pustywd
		var wdyuid []int64
		var userfsidarr []int64
		for _, u := range users {
			cunzai := 1
			for _, us := range userfsidarr {
				if u.ID == us {
					cunzai = 2
				}
			}
			if cunzai == 2 {
				continue
			}
			userfsidarr = append(userfsidarr, u.ID)
			//if u.Ceshiopenid != "" {
			//	Caigoucs(u.Ceshiopenid, strval, v.Procureid, u.ID)
			//}
			if u.Ywdgzheopenid != "" {
				//fmt.Println(u)
				data := Caigou(u.Ywdgzheopenid, strval, v.Procureid, u.ID)
				if data.Errcode == 43004 {
					wdyuid = append(wdyuid, u.ID)
				} else if data.Errcode == 42001 || data.Errcode == 40001 {
					resp, err := http.Get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appidywd + "&secret=" + appsecretywd)

					if err != nil {
						fmt.Println(err)
						return
					}
					defer resp.Body.Close()
					body, err := ioutil.ReadAll(resp.Body)
					r := ResponseAccess{}
					//fmt.Println("token----------", string(body))

					//把请求到的结构反序列化到专门接受返回值的对象上面
					err = json.Unmarshal(body, &r)
					if err != nil {
						fmt.Println(err)
					}
					weixintoken := r.AccessToken
					redis_lib.Client.Set(ctx, "weixinAccesstokendyewuduo", weixintoken, 7000*time.Second)
				} else if data.Errcode == 40003 {
					var weixin models.YwWeixin
					data_source.OtherDb.Select("id,openid").Where("unionid = ?", u.Unionid).First(&weixin)
					data_source.Db.Model(&models.User{}).Where("id = ?", u.ID).Update("ywdgzheopenid", weixin.Openid)
					data1 := Caigou(weixin.Openid, strval, v.Procureid, u.ID)

					jsonData, _ := json.Marshal(data1)
					pushadd := models.Pustywd{
						Uid:       u.ID,
						Procureid: v.Procureid,
						Addtime:   time.Now().Unix(),
						Content:   string(jsonData),
					}
					pushadds = append(pushadds, pushadd)
				} else {
					jsonData, _ := json.Marshal(data)
					pushadd := models.Pustywd{
						Uid:       u.ID,
						Procureid: v.Procureid,
						Addtime:   time.Now().Unix(),
						Content:   string(jsonData),
					}
					pushadds = append(pushadds, pushadd)
				}

			}

		}
		data_source.Db.Create(&pushadds)
		data_source.Db.Model(&models.User{}).Where("id in (?)", wdyuid).Update("ywddingyue", 3)
	}

	//var cids []string
	//for _, u := range user {
	//
	//	if u.Cid != "" {
	//		cids = append(cids, u.Cid)
	//	}
	//
	//}
	//service.Getuixx(cids, procure.Classifytitle)

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}

type WaloglistRBody struct {
	Data       []models.Walogsql `json:"data"`
	PageNo     int               `json:"pageNo"`
	PageSize   int               `json:"pageSize"`
	TotalCount int64             `json:"totalCount"`
	TotalPage  int64             `json:"totalPage"`
}

func Waloglist(ctx *gin.Context) {
	request := ProcuresBody{}
	ctx.ShouldBind(&request)
	endtime := request.Endtime
	paytime := request.Paytime
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64

	var users []models.Walogsql
	res := data_source.Db.Model(&models.Walog{}).Select("walog.*, user.phone, user.nickname").Joins("left join user on user.id = walog.uid")

	if paytime > 0 {
		res = res.Where("usertixian.addtime >= ?", paytime)
	}
	if endtime > 0 {
		res = res.Where("usertixian.addtime < ?", endtime+86400)
	}
	res.Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("walog.id desc").Find(&users)

	var totalPage int64
	if count > 0 {
		mo := count % int64(pageSize)
		if mo > 0 {
			totalPage = count/int64(pageSize) + 1
		} else {
			totalPage = count / int64(pageSize)
		}
	}

	data := WaloglistRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}
